package com.shp.controller;

import com.shp.pojo.Good;
import com.shp.pojo.ResultInfo;
import com.shp.pojo.ShopCartItem;
import com.shp.pojo.User;
import com.shp.service.ShopCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * Description:
 *
 * @author zwl
 * @version 1.0
 * @date 2020/2/27 23:07
 */
@Controller
@RequestMapping(value = "/shopcart")
public class ShopCartController {

    @Autowired
    private ShopCartService shopCartService;

    /**
     * 显示用户的购物车
     * @return
     */
    @RequestMapping(value = "/mycart",method = RequestMethod.GET)
    public String shopCart(HttpServletRequest request, Model model){
        //获取在线用户
        User activeUser = (User)request.getSession().getAttribute("activeUser");
        // 获取用户id
        Integer id = activeUser.getId();
        // 查询用户购物车信息
        List<ShopCartItem> cart = shopCartService.getShopCartByUserId(id);
        // 将购物车信息给前台
        model.addAttribute("cart",cart);
        return "goods/shopCart";
    }

    /**
     * 显示购物车的商品数量
     * @param session
     * @return
     */
    @RequestMapping(value = "/num",method = RequestMethod.GET)
    @ResponseBody
    public ResultInfo shopCartItemSize(HttpSession session){
        // 获取在线用户的id
        User activeUser = (User)session.getAttribute("activeUser");
        ResultInfo info = new ResultInfo();
        info.setFlag(true);
        info.setDatas(shopCartService.getShopCartItemSize(activeUser.getId()));
        return info;
    }

    /**
     * 移除购物车项
     * @param goods 需要移除商品的id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/remove",method = RequestMethod.POST)
    public ResultInfo removeShopCartItem(@RequestBody Good goods){
        ResultInfo info = new ResultInfo();
        boolean flag = shopCartService.removeShopCartItem(goods.getId());
        info.setFlag(flag);
        return info;
    }

    /**
     * 清空购物车
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/empty",method = RequestMethod.GET)
    public ResultInfo emptyShopCart(HttpSession session){
        ResultInfo info = new ResultInfo();
        // 获取在线用户的id
        User activeUser = (User)session.getAttribute("activeUser");
        boolean flag = shopCartService.empty(activeUser.getId());
        info.setFlag(flag);
        return info;
    }
}
